package com.demo.passenger.index.web;

import com.demo.passenger.sys.user.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class IndexWeb {


    @RequestMapping("toLogin")
    public String toLogin(){

        //return "login2";
        return null;
    }

    @RequestMapping("unAuth")
    public String unAuth(){

        return "";
    }

    @RequestMapping("logout")
    public String logout(){
        Subject subject= SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }


    @RequestMapping("login")
    @ResponseBody
    public Object login(HttpServletRequest request, SysUser user){

        Subject subject= SecurityUtils.getSubject();
        Map<String,Object> map=new HashMap<String,Object>();
        UsernamePasswordToken token=new UsernamePasswordToken(user.getLoginName(),user.getPassword());
        try {
            subject.login(token);

            SavedRequest savedRequest= WebUtils.getSavedRequest(request);
            String preUrl="/admin/index";
            if(savedRequest!=null && !savedRequest.getRequestUrl().equals("/")){
                preUrl=savedRequest.getRequestUrl();
            }
            map.put("url",preUrl);
            return map;
        }catch (UnknownAccountException e){
            map.put("msg","用户名不存在！");
            return map;
        }catch (IncorrectCredentialsException e){
            map.put("msg","密码错误！");
            return map;
        }
    }
}
